<?php
//error_reporting(E_ALL);
//ini_set('display_errors','1');


class email_marketing extends CI_Controller {

    private $dir = 'EmailMarketing';
    function __construct() {		

        parent::__construct();
         $this->is_login(2);
        $this->load->library('ion_auth');
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->library('pagination');
        $this->load->database();
        $this->lang->load('auth');
        $this->lang->load('admin_estate');
        $this->load->helper('language');
        $this->load->model('admin_estate_model');

		$this->load->helper('email');
		$this->load->helper('form');
		$this->load->helper('url');
		$this->load->helper('string');

        $this->load->model('mod_emailmarketing');
		$this->load->model('mod_users');
		$this->load->model('emailgroup_model');
		$this->load->model('codegen_model','',TRUE);
    }

    /**
	 * Loads Email settings page.
	 *
	 * @access	private
	 * @param	nil
	 * @return	void
	 */

	function index(){	
	   $data['message'] = $this->session->flashdata('message');

       $data['dir'] = $this->dir;
       $this->session->set_userdata('page', 22);
	   $this->load->model('emailtemplates_model');
	   $data['opened_email'] = $this->emailtemplates_model->subscribe();
	   
	   $data['ptitle'] = 'Email Marketing';
	   $this->tmadmin->tmView('email_marketing/index_view', $data);
	}
	//End of index function
	
	function template() {
		
		$start = $this->uri->segment(3);
		
		/*
		if ($start == '') {
			$start = 0;
		}
		
		$total_rows = $this->mod_emailmarketing->count_emailsettings();
		
		$config['uri_segment'] = 3;
		$config['base_url'] = site_url('email_marketing/template');
		$config['total_rows'] = $total_rows;
		$config['per_page'] =20;
		$config['next_link'] = "Next &raquo;";
		$config['prev_link'] = "&laquo; Previous";
		
		$this->pagination->initialize($config);
		$data['pagination_links'] = $this->pagination->create_links();
		$data['prev_next'] = $this->pagination->create_links();
		
		//Get All emailmarketing Termplates List
		
		$data['email_settings']	=	$this->mod_emailmarketing->getEmailSettings_with_count($limit = true, $start, $config['per_page']);
		
		$data['message'] = $this->session->flashdata('message');
		*/
		
		$data['dir'] = $this->dir;
		
		$data['page_title'] = 'Email Marketing Template';
		$data['page'] = 'emailmarketingtemplate';
		
		$data['ptitle'] = 'Email Marketing Template';
		$this->tmadmin->tmView('email_marketing/template', $data);
	}
	// End of template function
	
 	public function getdatatableajax()
    {
    	$this->load->model('emailtemplates_model');
    	 
    	$mail_stat[0]='Deactvate';
    	$mail_stat[1]='Actvate';
    	
    	$this->load->library('datatables');
    	
    	$opt = "
<div class='btn-group' style='margin:0;'> <a class=\"tooltp btn btn-warning btn-xs\" data-toggle=\"tooltip\" title='".$this->lang->line("edit_invoice")."' href='/index.php/email_marketing/edit_emailmarketing_template/$1'><i class=\"fa fa-edit\"></i></a> <a class=\"tooltp btn btn-danger btn-xs\" data-toggle=\"tooltip\" title='".$this->lang->line("delete_invoice")."' href='/index.php/email_marketing/delete_emailmarketing_template/$1' onClick=\"return confirm('Are you sure to delete this row?')\"><i class=\"fa fa-trash-o\"></i></a> </div>
";
    	
    	 
    	$this->datatables
    	->select("id, type, title, status",FALSE)
    	->from("email_templates")
    	->order_by('id','asc')
    	
		->add_column("Actions", $opt, "id")
		->edit_column('status', 'Activate', '1')
    	->unset_column('id');
    
    	echo $this->datatables->generate();
    }

	function alerts()
	{	
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Alerts';
       $data['page'] = 'alerts_view';

	   $data['ptitle'] = 'Alerts';
	   $this->tmadmin->tmView('email_marketing/alerts_view', $data);
	}

	function subscription()
	{	
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Subscriptions';
       $data['page'] = 'subscription';

	   $data['ptitle'] = 'Subscriptions';
	   $this->tmadmin->tmView('email_marketing/subscriptions_view', $data);
	}

	function filters()
	{	
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Filters';
       $data['page'] = 'filters_view';

	   $data['ptitle'] = 'Filters';
	   $this->tmadmin->tmView('email_marketing/filters_view', $data);
	}

	function mailing_list()
	{	
	   $data['user'] = $this->mod_users->get_user_list();
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Mailing lists';
	   
	   $data['ptitle'] = 'Mailing lists';
	   $this->tmadmin->tmView('email_marketing/mailing_list_view', $data);
	}
	
	function editTemplate()
	{

				$this->load->model('emailtemplatemodel');

				$outputData['emailTemplates_list'] = false;

				$outputData['emailTemplates_edit'] = true;

				$template_id = $this->uri->segment(4);

				$this->load->library('validation');

				$this->_emailtemplatesFrm();

				if (!isset($_POST['email_template']))

				{

						$outputData['templates'] = $this->emailtemplatemodel->readEmailTemplate($template_id);

						if ($outputData['templates'] != false) $outputData['templatesArr'] = $outputData['templates'];

				}

				if (isset($_POST['cancel_template'])) redirect('admin/emailTemplates');

				if ($this->validation->run() == false) $outputData['validationError'] = $this->validation->error_string;

				else

				{

						if (isset($_POST['email_template']))

						{

								$this->emailtemplatemodel->updateEmailTemplate($_POST);

								//Set the flash data

								$this->session->set_flashdata('successMsg', $this->lang->line('emailtemplates_success_msg'));

								redirect('admin/emailTemplates/editTemplate/' . $_POST['template_key']);

						}

				}

				$this->smartyextended->view('../admin/emailtemplates', $outputData);

		}

		

		

		

		

		function _emailtemplatesFrm()

		{

				$rules['template_subject'] = 'trim|required|alphanumeric';

				$rules['template_content'] = 'trim|required|alphanumeric';

				$fields['template_subject'] = $this->lang->line('emailtemplates_mail_subject');

				$fields['template_content'] = $this->lang->line('emailtemplates_mail_content');

				$this->validation->set_rules($rules);

				$this->validation->set_fields($fields);

		}

		

		// --------------------------------------------------------------------

				

	/**

	 * Edit emailmarketingSettings.

	 *

	 * @access	private

	 * @param	nil

	 * @return	void

	 */

	function edit_emailmarketing_template()
	{	
		//Get id of the category	
		$id = is_numeric($this->uri->segment(3))?$this->uri->segment(3):0;

		$this->load->helper('form');

		//Intialize values for library and helpers	
		$this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

		if($this->input->post('editEmailSetting'))
		{
			
			//Set rules
			$this->form_validation->set_rules('email_subject','email_subject_validation','required|trim|xss_clean');
			$this->form_validation->set_rules('email_body','email_body_validation','required|trim|xss_clean');

			if($this->form_validation->run() == TRUE)
			{	
				  $updateData                  		= array();	
			      $updateData['mail_subject '] 	    = $this->input->post('email_subject');
				  $updateData['mail_body']  		= $this->input->post('email_body');
				  $updateData['start_date']  		= $this->input->post('start_date');
				  $updateData['end_date']  		= $this->input->post('end_date');
				  $updateData['status']  		= $this->input->post('status');
				  
				  $prefix = '';
				  $ids = '';
				  foreach($_POST['usergroup_name'] as $list) {
					$ids .= $prefix ." ".$list;
					$prefix = ',';
				  }
				  $updateData['usergroup_name']  	= $ids;	

				  //Update Email Settings
				  $this->mod_emailmarketing->updateEmailSettings($id,$updateData);			  

				  //Notification message
				  $this->session->set_flashdata('message', "EmailMarketing Template Updated successfully");

				  redirect('email_marketing/template');
		 	} 

		} //If - Form Submission End

		//Set Condition To Fetch The Email Settings info
		$condition = array('id'=>$id);

		//Get Email Settings
	   $data['emailSettings']	=	$this->mod_emailmarketing->getEmailSettings($condition);

		//Load View
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Edit Email Marketing Template';
       $data['page'] = 'edit_emailmarketingtemplate';
	   
	   $data['group_list'] = $this->emailgroup_model->getall_emailgroups();
	   	   
	   $data['ptitle'] = 'Mailing lists';
	   $this->tmadmin->tmView('email_marketing/edit_emailmarketingSettings', $data);
	}//End of editemailmarketingSettings function

	

	/* Add new email settings

	

	/**

	 * delete EmailSettings.

	 *

	 * @access	private

	 * @param	nil

	 * @return	void

	 */

	function delete_emailmarketing_template()
	{	
		//Get id of the category	
		$id = is_numeric($this->uri->segment(3))?$this->uri->segment(3):0;
		$condition = array('email_templates.id'=>$id);

		$this->mod_emailmarketing->deleteEmailSettings($condition);

		//Notification message

	    $this->session->set_flashdata('message', "Email Marketing Template deleted successfully");

		redirect('email_marketing/template');

	}	//function end	

//---------------------------------------------



     /**

	 * add EmailSettings.

	 *

	 * @access	private

	 * @param	nil

	 * @return	void

	 */

	function add_emailmarketing_template()
	{//load validation library
		
		//Load Form Helper
		$this->load->helper('form');

		//Intialize values for library and helpers	
		$this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

		if($this->input->post('addEmailSetting'))
		{	
			//Set rules
			$this->form_validation->set_rules('email_title','lang:Newsleter Setting Title','required|trim|xss_clean|callback_categoryNameCheck');
			$this->form_validation->set_rules('email_subject','lang:Newsleter Setting SUbject','required|trim|xss_clean');
			$this->form_validation->set_rules('email_body','lang:Newsleter Setting Body','required|trim|xss_clean');
			$this->form_validation->set_rules('start_date','lang:Newsleter Start Date');

			if($this->form_validation->run())
			{	
				  //prepare update data
				  $insertData                  		= array();	
			      $insertData['id']                 = '';
				  $insertData['type']  				= $this->input->post('email_type');
				  $insertData['title']  			= $this->input->post('email_title');
				  $insertData['mail_subject '] 	    = $this->input->post('email_subject');
				  $insertData['mail_body']  		= $this->input->post('email_body');
				  $insertData['start_date']  		= $this->input->post('start_date');
				  $insertData['end_date']  			= $this->input->post('end_date');
				  
				  $prefix = '';
				  $ids = '';
				  foreach($_POST['usergroup_name'] as $list) {
					$ids .= $prefix ." ".$list;
					$prefix = ',';
				  }

				  $insertData['usergroup_name']  	= $ids;	

				  //add Email Settings
				  $this->mod_emailmarketing->addEmailSettings($insertData);  

				  //Notification message
				  $this->session->set_flashdata('msg', "EmailMarketing Template added successfully");

				  redirect('email_marketing/template');
		 	} 

		} //If - Form Submission End				

		//Load View

	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Add Email Marketing Template';
       $data['page'] = 'add_emailmarketingtemplate';
	   
	   $data['group_list'] = $this->emailgroup_model->getall_emailgroups();
	   
	   $data['ptitle'] = 'Add Email Marketing Template';
	   $this->tmadmin->tmView('email_marketing/add_emailmarketingSettings', $data);
	}



	public function settings()
	{
	  if($this->input->post('update')){

 		$data1['value']     = $this->input->post('mailer_type');
		$this->db->where('code', 'MAILER_TYPE');
		$this->db->update('email_settings',$data1);

		$data2['value']    = $this->input->post('smtp_port');

		$this->db->where('code', 'SMTP_PORT');
		$this->db->update('email_settings',$data2);

		$data3['value']    = $this->input->post('smtp_user');
		$this->db->where('code', 'SMTP_USER');
		$this->db->update('email_settings',$data3);

		$data4['value']    = $this->input->post('smtp_pass');
		$this->db->where('code', 'SMTP_PASS');
		$this->db->update('email_settings',$data4);

		$data5['value']    = $this->input->post('mailer_mode');
		$this->db->where('code', 'MAILER_MODE');
		$this->db->update('email_settings',$data5);

		$this->session->set_flashdata('message', "Email Marketing settings updated successfully");

		redirect('email_marketing/settings');
			
	} else {

			$query1                  = $this->db->get_where('email_settings', array('code' => 'MAILER_TYPE'));
			$data['mailer_type']     = $query1->row()->value;

			$query2                  = $this->db->get_where('email_settings', array('code' => 'SMTP_PORT'));
			$data['smtp_port']       = $query2->row()->value;

			$query3                  = $this->db->get_where('email_settings', array('code' => 'SMTP_USER'));
			$data['smtp_user']       = $query3->row()->value;
			
			$query4                  = $this->db->get_where('email_settings', array('code' => 'SMTP_PASS'));
			$data['smtp_pass']       = $query4->row()->value;

			$query5                  = $this->db->get_where('email_settings', array('code' => 'MAILER_MODE'));
			$data['mailer_mode']     = $query5->row()->value;

			$data['message'] = $this->session->flashdata('message');
       		$data['dir'] = $this->dir;
		    $data['page_title'] = 'Email Marketing Settings';
		    $data['page'] = 'settings';
		    //$data['content'] = $this->load->view('email_marketing/settings',$data,true);

		    //$this->load->view('admin/dashbord',$data);
		    
		    $data['ptitle'] = 'Email Marketing Settings';
		    $this->tmadmin->tmView('email_marketing/settings', $data);
		}
   }

	

	public function mass_campaigns()
	{
		$this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

	 	if($this->input->post('submit'))
		{
			//Set rules
			$this->form_validation->set_rules('subject','Subject','required|trim|xss_clean');
			$this->form_validation->set_rules('message','Message','required|trim|xss_clean');

			if($this->form_validation->run())
			{
				$subject = $this->input->post('subject');
				$message = $this->input->post('message');
				
				$admin_email = 'admin@admin.com';//$this->dx_auth->get_site_sadmin();

				if($this->input->post('is_private') == 1)
				{
					$emails    = $this->input->post('email_to'); 
					$mail_list = explode(',',$emails);

					$message .= '
<div><img src="http://software.epicinfosoft.com/index.php/track_email?newsletter_id=1&email='.$emails.'&status=1"/></div>
'; 

					if(!empty($mail_list))
					{
							foreach($mail_list as $email_to)
							{  
									if(valid_email($email_to))
									{
											$toEmail      = $email_to;
											$fromEmail    = $admin_email;
											$fromName     = 'Shopper-Base.com';

											$email_name   = 'admin_mass_email';
											$email_name .= '
<div><img src="http://software.epicinfosoft.com/index.php/EmailMarketing/track_email?newsletter_id=1&email='.$toEmail.'&status=1"/></div>
'; 

											$splVars = array("{site_name}" => 'Shopper-Base.com', "{dynamic_content}" => $message, "{subject}" => $subject);
											

											$this->mod_emailmarketing->sendMail($toEmail,$fromEmail,$fromName,$email_name,$splVars);
											$this->load->model('admin/emailtemplates_model');
											$post['newsletter_id'] = 1;
											$post['email'] = $toEmail;
											$this->emailtemplates_model->track_insert($post);
									}
							}	

					}
				}
				else
				{
					$this->db->where('id !=', 1);
					$users = $this->db->get('users')->result();
					
					foreach($users as $user) {  
						$toEmail      = $user->email;
						$fromEmail    = $admin_email;
						$fromName     = 'mynextproject';//$this->dx_auth->get_site_title();

						$email_name   = 'admin_mass_email';
						$email_name .= '
<div><img src="http://software.epicinfosoft.com/index.php/EmailMarketing/track_email?newsletter_id=1&email='.$toEmail.'&status=1"/></div>
'; 

						$splVars = array("{site_name}" => 'mynextproject', "{dynamic_content}" => $message, "{subject}" => $subject);

						$this->mod_emailmarketing->sendMail($toEmail,$fromEmail,$fromName,$email_name,$splVars);
						$this->load->model('admin/emailtemplates_model');
						$post['newsletter_id'] = 1;
						$post['email'] = $toEmail;
						$this->emailtemplates_model->track_insert($post);
					}
				}

				$this->session->set_flashdata('msg', "Mail sent successfully");

				redirect('email_marketing/mass_campaigns');
			}
	  }
	  $data['msg'] = $this->session->flashdata('msg');
  	  $data['dir'] = $this->dir;

	  $data['ptitle'] = 'Mass Email Marketing Campaigns';
	  $this->tmadmin->tmView('email_marketing/mass_emailmarketing', $data);
	}
	
	public function send_email_demo()
	{		   	 
	   $this->load->library('email');
	
		$this->email->from('anant101289@gmail.com', 'Anant');
		//$this->email->to('testmagento111@gmail.com');
		$this->email->to('testmagento111@gmail.com');
		//$this->email->bcc('hitesh.patel94@gmail.com');
		$this->email->set_mailtype('html');
		
	    $this->email->subject('Email Test');
		  $message = "Test Message";
		
		  $message .= '
<div><img src="http://software.epicinfosoft.com/index.php/EmailMarketing/track_email?newsletter_id=2&email=anant101289@gmail.com&status=1"/></div>
';   
		 
		$this->email->message($message);
		
		//$this->email->send();
		if($this->email->send())
		{
	    	echo "Your email was sent successfully";
		} else {
			show_error($this->email->print_debugger());
		}
	}
	
	public function track_email()
	{	
	 	$this->load->model('admin/emailtemplates_model');
		$this->emailtemplates_model->track_update($_GET);
	}
	
	public function email_subscribe()
	{	
		$this->load->model('admin/emailtemplates_model');
		$this->emailtemplates_model->subscribe();		
	}
	
	function sent_mail()
	{	
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Send Email';
       $data['page'] = 'send_email';

	   $this->load->model('emailtemplates_model');
	   $data['send_email_data'] = $this->emailtemplates_model->send_mail_listing();
	   
	   $data['ptitle'] = 'Send Email';
	   $this->tmadmin->tmView('email_marketing/send_mail_view', $data);
	}
	
	public function delete_send_email()
	{	
		$this->load->model('admin/emailtemplates_model');
		$this->emailtemplates_model->deleteSendEmail($_GET['id']);
		$this->session->set_flashdata('msg', 'Successfull Delete Record');	
		redirect('email_marketing/sent_mail');
	}
	
	function hot_leads()
	{	
	   $data['msg'] = $this->session->flashdata('msg');
       $data['dir'] = $this->dir;
       $data['page_title'] = 'Open Email';
       $data['page'] = 'hot_leads';

	   $this->load->model('emailtemplates_model');
	   $data['open_email_data'] = $this->emailtemplates_model->open_mail_listing();
	   
	   $data['ptitle'] = 'Hot Leads';
	   $this->tmadmin->tmView('email_marketing/open_mail_view', $data);
	}
	public function delete_open_email()
	{	
		$this->load->model('admin/emailtemplates_model');
		$this->emailtemplates_model->deleteOpenEmail($_GET['id']);
		$this->session->set_flashdata('msg', 'Successfull Delete Record');	
		redirect('email_marketing/hot_leads');
	}
//Imtiaz
 public function is_login($level = 2) {
        if (!$this->ion_auth->logged_in()) {
            //redirect them to the login page
            redirect('login', 'refresh');
        } elseif (!$this->ion_auth->is_admin($level)) {
            $this->load->helper('admin');
            redirect(site_url(), 'refresh');
        }
    }
			
			private function add_subscibers()
			{
				 $this->load->library('form_validation');    
					$this->data['custom_error'] = '';
		
				if ($this->form_validation->run('mw_list_subscriber') == false)
				{
					 $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
		
				} else
				{                            
					$data = array(
							'subscriber_uid' => random_string('alnum', 13), 
							'list_id' => $this->uri->segment(5),
							'email' => set_value('email'),
							'status' => set_value('status'),
							'date_added' => $this->codegen_model->get_date(),
							'last_updated' => $this->codegen_model->get_date()
					);	
					if ($this->codegen_model->add('mw_list_subscriber',$data) == TRUE)
					{
						$subscriber_id = $this->db->insert_id();																		
						$data = array(
							array(
								'field_id' => '7' , 
								'subscriber_id' => $subscriber_id,
								'value' => set_value('email'),
								'date_added' => $this->codegen_model->get_date(),
								'last_updated' => $this->codegen_model->get_date()
							),
							array(
								'field_id' => '8' , 
								'subscriber_id' => $subscriber_id,
								'value' => $this->input->post('first_name'),
								'date_added' => $this->codegen_model->get_date(),
								'last_updated' => $this->codegen_model->get_date()
							),
							array(
								'field_id' => '9' , 
								'subscriber_id' => $subscriber_id,
								'value' => $this->input->post('last_name'),
								'date_added' => $this->codegen_model->get_date(),
								'last_updated' => $this->codegen_model->get_date()
							)
							
							);	
							$this->db->insert_batch('mw_list_field_value',$data);	
							redirect('email_marketing/lists');				
					
					}
					else
					{
						echo "error";
					}
				}
				$this->tmadmin->tmView('email_marketing/list_subscriber_add', $data);
			}	
							
	public function lists($operation,$parameter)
	{			
				if($operation=='subscribers')
				{
					$method=$this->uri->segment(4);
					if($method=='create')
					{
						$this->add_subscibers();
						
					}
				}	
				else if(method_exists($this,$operation))
				{
					$this->$operation();
				}
				else{
				
				$data['message'] = $this->session->flashdata('message');
				$data['dir'] = $this->dir;
			    $this->session->set_userdata('page', 22);		
				$this->load->model('list_model');
				$data['subscribers_lists'] = $this->list_model->get_list_subscribers();						
			 	$this->tmadmin->tmView('email_marketing/list_index', $data);
				}
		
	}
		
				
		private function create(){        
		
        $this->load->library('form_validation');   
		$this->form_validation->set_error_delimiters('<p class="error">','</p>');
		$this->form_validation->set_message('required', '%s cannot be blank');
		$data['custom_error'] = '';
		
        if ( $this->form_validation->run('mw_list_validation') == false)
        {
             $data['custom_error_un'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);

        } else
        {                
		
		             
            $data_list = array(   
				   'list_uid' => random_string('alnum', 13), 
				   'user_id' => $this->session->userdata('user_id'),
					'name' => set_value('name'),
					'description' => set_value('description'),					
					'opt_in' => set_value('opt_in'),
					'opt_out' => set_value('opt_out'),
					'date_added' => $this->codegen_model->get_date(),
					'last_updated' => $this->codegen_model->get_date(),
					
            );
			
			
			
			
           
			if ($this->codegen_model->add('mw_list',$data_list) == TRUE)
			{
				$data['custom_error'] = '<div class="form_error"><p>Working.</p></div>';
				$list_id = $this->db->insert_id();
				$data_list_default = array(
	     			'list_id' =>$list_id ,   
                    'from_name' => set_value('from_name'),
					'from_email' => set_value('from_email'),
					'reply_to' => set_value('reply_to'),
					'subject' => set_value('subject')
            );
			$data_list_notifications = array(  
					'list_id' =>$list_id ,				            
					'subscribe' => set_value('subscribe'),
					'unsubscribe' => set_value('unsubscribe'),				
					'subscribe_to' => set_value('subscribe_to'),
					'unsubscribe_to' => set_value('unsubscribe_to')
            );
			$data_list_company = array(
					'list_id' =>$list_id , 
                    'country_id' => $this->input->post('country_id'),
					'zone_id' => $this->input->post('zone_id'),
					'name' => $this->input->post('company_name'),
					'address_1' => $this->input->post('address_1'),
					'address_2' => $this->input->post('address_2'),
					'zone_name' => $this->input->post('zone_name'),
					'city' => $this->input->post('city'),
					'zip_code' => $this->input->post('zip_code'),
					'phone' => $this->input->post('phone'),
					'address_format' => $this->input->post('address_format')
            );
				if($this->codegen_model->add('mw_list_default',$data_list_default) == TRUE)
				{
					if ($this->codegen_model->add('mw_list_customer_notification',$data_list_notifications) == TRUE)					
					{
						if ($this->codegen_model->add('mw_list_company',$data_list_company) == TRUE)
						{  
						redirect('email_marketing/lists');
						}
					}
					
				}
				//$this->data['custom_error'] = '<div class="form_ok"><p>Added</p></div>';
			
				
			}
			else
			{
				$data['custom_error'] = '<div class="form_error"><p>An Error Occured.</p></div>';

			}
			
			
			
		}
		$data['countries'] = $this->db->get('mw_country')->result();;
				   
		$this->tmadmin->tmView('email_marketing/list_create', $data);
        //$this->template->load('content', 'mw_list_add', $this->data);
    }	
    
   private function edit(){               
   
   $this->load->library('form_validation');   
		$this->form_validation->set_error_delimiters('<p class="error">','</p>');
		$this->form_validation->set_message('required', '%s cannot be blank');
		$data['custom_error'] = '';
		
        if ( $this->form_validation->run('mw_list_validation') == false)
        {
             $data['custom_error_un'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);

        } else
        {                
		$datestring = "%Y-%m-%d  %h:%i:$s";
		$time = time();
		             
            $data_list = array(   
				   'list_uid' => random_string('alnum', 13), 
				   'user_id' => $this->session->userdata('user_id'),
					'name' => set_value('name'),
					'description' => set_value('description'),					
					'opt_in' => set_value('opt_in'),
					'opt_out' => set_value('opt_out'),
					'date_added' => mdate($datestring, $time),
					'last_updated' => mdate($datestring, $time),
					
            );
			
			
			
			
           
			if ($this->codegen_model->edit('mw_list',$data_list,'list_id' ,$this->uri->segment(4)) == TRUE)
			{
				$data['custom_error'] = '<div class="form_error"><p>Working.</p></div>';				
				$data_list_default = array(	     		
                    'from_name' => set_value('from_name'),
					'from_email' => set_value('from_email'),
					'reply_to' => set_value('reply_to'),
					'subject' => set_value('subject')
            );
			$data_list_notifications = array(  					            
					'subscribe' => set_value('subscribe'),
					'unsubscribe' => set_value('unsubscribe'),				
					'subscribe_to' => set_value('subscribe_to'),
					'unsubscribe_to' => set_value('unsubscribe_to')
            );
			$data_list_company = array(					
                    'country_id' => $this->input->post('country_id'),
					'zone_id' => $this->input->post('zone_id'),
					'name' => $this->input->post('company_name'),
					'address_1' => $this->input->post('address_1'),
					'address_2' => $this->input->post('address_2'),
					'zone_name' => $this->input->post('zone_name'),
					'city' => $this->input->post('city'),
					'zip_code' => $this->input->post('zip_code'),
					'phone' => $this->input->post('phone'),
					'address_format' => $this->input->post('address_format')
            );
				if($this->codegen_model->edit('mw_list_default',$data_list_default,'list_id' ,$this->uri->segment(4)) == TRUE)
				{
					if ($this->codegen_model->edit('mw_list_customer_notification',$data_list_notifications,'list_id' ,$this->uri->segment(4)) == TRUE)					
					{
						if ($this->codegen_model->edit('mw_list_company',$data_list_company,'list_id' ,$this->uri->segment(4)) == TRUE)
						{  
						redirect('email_marketing/lists');
						}
					}
					
				}
				//$this->data['custom_error'] = '<div class="form_ok"><p>Added</p></div>';
			
				
			}
			else
			{
				$data['custom_error'] = '<div class="form_error"><p>An Error Occured.</p></div>';

			}
			
			
			
		}
		$result = $this->db->get_where('mw_list', array('list_id' => $this->uri->segment(4)));		
		$data['list'] = $result->row_array();		
		$result = $this->db->get_where('mw_list_default', array('list_id' => $this->uri->segment(4)));
		$data['list_default'] = $result->row_array();			
		$result = $this->db->get_where('mw_list_customer_notification', array('list_id' => $this->uri->segment(4)));	
		$data['list_customer_notification'] = $result->row_array();	
		$result = $this->db->get_where('mw_list_company', array('list_id' => $this->uri->segment(4)));	
		$data['list_company'] = $result->row_array();	

		$this->tmadmin->tmView('email_marketing/list_edit', $data);	
		
		
        //$this->template->load('content', 'mw_list_edit', $this->data);
    }
	
    private function delete(){
            $ID =  $this->uri->segment(4);
            $this->codegen_model->delete('mw_list_company','list_id',$ID);
			$this->codegen_model->delete('mw_list_customer_notification','list_id',$ID);
			$this->codegen_model->delete('mw_list_default','list_id',$ID);
			$this->codegen_model->delete('mw_list','list_id',$ID);             
            redirect('email_marketing/lists');
    }
	private function overview()
	{
		$data['message'] = $this->session->flashdata('message');
				$data['dir'] = $this->dir;
			    $this->session->set_userdata('page', 22);		
				$this->load->model('list_model');
				$data['subscribers_lists'] = $this->list_model->get_list_subscribers();						
			 	$this->tmadmin->tmView('email_marketing/list_overview', $data);
		
	}
	
	function getcountry($id)
	{
		$datavalues=$this->db->get_where('mw_zone',array('country_id' => $id))->result();
		$this->output->set_output(json_encode($datavalues));	
		
	}
	
	
	function add_subscriber()
	{
		
	}
				
	}

//End  emailmarketing Class



/* End of file emailmarketing.php */ 

/* Location: ./app/controllers/admin/emailmarketing.php */